<template>
<div>
  <div class="search">
      <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音">
  </div>
  <div class="search-content" ref="search" v-show="keyword">
      <ul>
          <li
           class="search-item border-bottom" 
           v-for="item of list" 
           :key="item.id"
           @click='handleCityClick(item.name)'
          >
           {{item.name}}
           </li>
           <li class="search-item border-bottom" v-show='Hasnodata'>
               没有找到匹配数据
           </li>
      </ul>
  </div>
</div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
    name:'CitySearch',
    props:{
        cities:Object,//接收父组件传来的数据
    },
    methods:{
        handleCityClick(city){
            // console.log(city)//city为什么能获得点击的数据???
            // this.$store.commit('changeCity',city);
            this.changeCity(city);
            this.$router.push('/');//xunan选择后立即实现页面跳转
        },
        ...mapMutations(['changeCity'])
    },
    data(){
        return{
            keyword:'',//v-model双向绑定数据
            list:[],//作为搜索反馈的内容实际显示在界面（v-for）
            timer:null//节流优化
        }
    },
    computed:{//没有搜索到匹配项时
        Hasnodata(){
            return !this.list.length;//即length=0时显示
        }
    },
    watch:{
        keyword(){
            if(this.timer){//节流
                clearTimeout(this.timer)
            }
            if(!this.keyword){//搜索框没有值时，list数组清空，即页面清空
              return this.list=[];
            }
            this.timer=setTimeout(()=>{
                const result=[];
                for(let i in this.cities){//遍历数据(cities是对象)
                    this.cities[i].forEach((value)=>{//遍历里面的数组，对应A:[...],B[...]...
                        if(value.spell.indexOf(this.keyword)>-1||
                           value.name.indexOf(this.keyword)>-1){//条件判断对于数组里的spell和name(拼音和文字)在搜到的情况下push进result数组
                            result.push(value);
                        }
                    })
                }
                this.list=result;//把外部list数组和result链接
            },100)
        }
    },
    mounted(){//此时页面已经渲染完成
      this.scroll=new BScroll(this.$refs.search);//实现向下滑动功能
    }
}
</script>

<style scoped>
.search{
    background:#00bcd4;
    height: 0.72rem;
    padding: 0 0.1rem;
}
.search-input{
    box-sizing: border-box;
    padding:0 0.1rem;
    width:100%;
    height: 0.62rem;
    line-height:0.62rem;
    text-align: center;
    border-radius:0.05rem;
    color:#666;
}
.search-content{
    position: absolute;
    top:1.58rem;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 3;
    overflow: hidden;
    background: #eee;
}
.search-item{
    line-height: 0.62rem;
    background: #fff;
    padding-left:0.2rem;
}
</style>